import { Popconfirm, Button, Divider, Dropdown, Form, Icon, Menu, message } from 'antd';
import React, {useRef, useState} from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import ProTable, {ActionType, ProColumns, UseFetchDataAction} from '@ant-design/pro-table';
import {  queryCourse ,takeCourse } from './service';
import {TableListItem} from "@/pages/Course/data";
import router from 'umi/router';

const TableList: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const [stateloading,setstateloading] = useState(-1);
  const take = async (fields: TableListItem[]) => {
    console.log(fields);
    setstateloading(fields.key);
    if(fields.flag == true){
      setstateloading(-1);
      message.error('你已经选了这课程了，试试其他吧');
      return
    }
    if(fields.people_num <= 0){
      setstateloading(-1);
      message.error('此课程已经被抢光啦，请试试其他');
      return
    }
    const hide = message.loading('正在抢课');
    if(!localStorage.getItem('antd_pro_id')){
      hide();
      message.error('请先登录');
      router.push('/user/login');
      return
    }


    try {
      let result = await takeCourse({
        id: localStorage.getItem('antd_pro_id'),
        course_id : fields.key
      });
      if(result.msg == "课程已经被抢完了"){
        message.error('课程已经被抢完了');
        hide();
        setstateloading(-1);
        return false;
      }
      hide();
      setstateloading(-1);
      actionRef.current.reload();
      message.success('抢课成功');
      return true;
    } catch (error) {
      hide();
      message.error('抢课失败，请重试');
      return false;
    }
  };

  const [setStepFormValues] = useState({});
  const columns = [
    {
      title: '课程名称',
      dataIndex: 'course_name',
    },
    {
      title: '系部名称',
      dataIndex: 'department_name',
    },
    {
      title: '人数',
      dataIndex: 'people_num',
    },
    {
      title: '时间',
      dataIndex: 'time',
    },
    {
      title: '教室',
      dataIndex: 'classroom_name',
    },
    {
      title: '教师',
      dataIndex: 'teacher_name',
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <>
            <Button type="primary" loading={record.key == stateloading} onClick={()=>{take(record)}}
                    disabled={record.flag == true || record.people_num <= 0}>
              {record.flag == true ? '已抢' : ''}
              {record.people_num <= 0 && record.flag != true ? '人数已满' : ''}
              {record.people_num > 0 && record.flag != true ? '抢课' : ''}
            </Button>
        </>
      ),
    },
  ];

  return (
    <PageHeaderWrapper>
      <ProTable<TableListItem>
        headerTitle="查询表格"
        actionRef={actionRef}
        rowKey="key"
        request={params => queryCourse(params)}
        columns={columns}
        />
    </PageHeaderWrapper>
);
};

export default TableList;
